package com.ruoyi.carton.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.carton.domain.*;
import com.ruoyi.carton.domain.vo.OrdersAndBoxVO;
import com.ruoyi.carton.domain.vo.OrdersDetailVO;
import com.ruoyi.carton.domain.vo.OrdersQuery;
import com.ruoyi.carton.mapper.OrdersMapper;
import com.ruoyi.carton.service.*;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* @author 时空
* @description 针对表【orders(订单主表)】的数据库操作Service实现
* @createDate 2025-06-28 13:26:44
*/
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders>
    implements OrdersService{

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderRequestService orderRequestService;
    @Autowired
    private OrderInboundService orderInboundService;
    @Autowired
    private OrderOutboundService orderOutboundService;
    @Autowired
    private BoxService boxService;
    @Autowired
    private CardboardService cardboardService;


    @Override
    public List<Orders> selectOrdersList(Orders orders) {
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();

        if (StringUtils.isNotBlank(orders.getId())) {
            queryWrapper.eq(Orders::getId, orders.getId());
        }
        if (StringUtils.isNotBlank(orders.getCustomerName())) {
            queryWrapper.like(Orders::getCustomerName, orders.getCustomerName());
        }
        if (orders.getStatus() != null) {
            queryWrapper.eq(Orders::getStatus, orders.getStatus());
        }

        return this.list(queryWrapper);
    }

    @Override
    public List<OrdersDetailVO> selectOrdersDetailList(OrdersQuery query) {
        return baseMapper.selectOrdersDetailList(query);
    }

//    @Override
//    public int updateStatusById(String id) {
//        Orders order = ordersMapper.selectById(id);
//        if (order == null) {
//            throw new RuntimeException("订单不存在");
//        }
//        OrderStatus currentStatus = order.getStatus();
//        if (currentStatus == OrderStatus.OUT_STOCK) {
//            throw new RuntimeException("订单已出库，状态不可更改");
//        }
//        OrderStatus nextStatus = getNextStatus(currentStatus);
//        order.setStatus(nextStatus);
//        this.updateById(order);  // 更新状态
//        // 创建对应子表
//        switch (nextStatus) {
//            case REQUESTED:
//                orderRequestService.createOrderRequest(order);
//                break;
//            case IN_STOCK:
//                orderInboundService.createInboundReceipt(order);
//                break;
//            case OUT_STOCK:
//                orderOutboundService.createOutboundReceipt(order);
//                break;
//            default:
//                break;
//        }
//        return 1;
//
//
//    }
//
//    private OrderStatus getNextStatus(OrderStatus current) {
//        switch (current) {
//            case DRAFT:
//                return OrderStatus.REQUESTED;
//            case REQUESTED:
//                return OrderStatus.IN_STOCK;
//            case IN_STOCK:
//                return OrderStatus.OUT_STOCK;
//            default:
//                throw new IllegalStateException("已是最终状态，无法推进");
//        }
//    }

    @Override
    public int updateStatusById(String id) {
        Orders order = ordersMapper.selectById(id);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }

        OrderStatus currentStatus = order.getStatus();
        if (currentStatus == OrderStatus.OUT_STOCK) {
            throw new ServiceException("订单已出库，状态不可更改");
        }

        OrderStatus nextStatus = getNextStatus(currentStatus);

        // 先创建对应子表，成功后再更新状态
        switch (nextStatus) {
            case REQUESTED:
                orderRequestService.createOrderRequest(order);
                break;
            case IN_STOCK:
                orderInboundService.createInboundReceipt(order);
                break;
            case OUT_STOCK:
                orderOutboundService.createOutboundReceipt(order);
                break;
            default:
                throw new ServiceException("状态转换异常");
        }

        // 子表插入成功后再更新状态
        order.setStatus(nextStatus);
        boolean updated = this.updateById(order);
        if (!updated) {
            throw new ServiceException("状态更新失败");
        }

        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteOrderAndChildren(String id) {
        Orders order = this.getById(id);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }

        String productId = order.getProductId();

        // 1. 删除 order_request
        LambdaQueryWrapper<OrderRequest> reqWrapper = new LambdaQueryWrapper<>();
        reqWrapper.eq(OrderRequest::getOrderId, id);
        List<OrderRequest> requests = orderRequestService.list(reqWrapper);

        // 提取纸板ID集合
        List<String> cardboardIds = requests.stream()
                .map(OrderRequest::getCardboardId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());

        orderRequestService.remove(reqWrapper);

        // 2. 删除入库单
        orderInboundService.remove(new LambdaQueryWrapper<OrderInbound>()
                .eq(OrderInbound::getOrderId, id));

        // 3. 删除出库单
        orderOutboundService.remove(new LambdaQueryWrapper<OrderOutbound>()
                .eq(OrderOutbound::getOrderId, id));

        // 4. 删除订单
        this.removeById(id);

        // 5. 删除 box（根据 productId）
        if (StringUtils.isNotEmpty(productId)) {
            boxService.removeById(productId);
        }

        // 6. 删除 cardboard（根据前面查到的）
        if (CollectionUtils.isNotEmpty(cardboardIds)) {
            cardboardService.removeByIds(cardboardIds);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addOrderAndBox(OrdersAndBoxVO vo) {
        if (StringUtils.isBlank(vo.getId())) {
            throw new ServiceException("订单ID不能为空");
        }
        if(StringUtils.isBlank(vo.getProductId())){
            throw new ServiceException("产品ID不能为空");
        }
        //判断订单是否存在
        Orders existOrder = this.getById(vo.getId());
        if(existOrder != null){
            throw new ServiceException("订单ID已存在");
        }
        //判断产品是否存在
        Box existBox = boxService.getById(vo.getProductId());
        if(existBox!= null){
            throw new ServiceException("产品ID已存在");
        }

        // 构造 Box 实体
        Box box = new Box();
        box.setId(vo.getProductId());
        box.setProductName(vo.getProductName());
        box.setLength(vo.getLength());
        box.setWidth(vo.getWidth());
        box.setHeight(vo.getHeight());
        box.setOrderQuantity(vo.getOrderQuantity());
        box.setFluteType(vo.getFluteType());

        BigDecimal salePrice = vo.getSalePrice() != null ? vo.getSalePrice() : BigDecimal.ZERO;
        BigDecimal rebate = vo.getRebate() != null ? vo.getRebate() : BigDecimal.ZERO;
        box.setSalePrice(salePrice);
        box.setRebate(rebate);
        box.setProfit(salePrice.subtract(rebate));
        box.setArea(vo.getArea() != null ? vo.getArea() : BigDecimal.ZERO);

        boxService.save(box);
        // 构造 Orders 实体
        Orders order = new Orders();
        order.setId(vo.getId());
        order.setCustomerName(vo.getCustomerName());
        order.setProductId(vo.getProductId());
        order.setStatus(OrderStatus.DRAFT);
        order.setEntryDate(new Date());
        this.save(order);

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void UpdateOrderAndBox(OrdersAndBoxVO vo) {
        // 校验订单ID
        if (StringUtils.isBlank(vo.getId())) {
            throw new ServiceException("订单ID不能为空");
        }
        // 查询订单是否存在
        Orders existOrder = this.getById(vo.getId());
        if (existOrder == null) {
            throw new ServiceException("订单不存在");
        }
        // 获取订单中绑定的产品ID（box id）
        String productId = existOrder.getProductId();
        if (StringUtils.isBlank(productId)) {
            throw new ServiceException("订单未关联产品，无法修改");
        }
        // 查询 Box 是否存在
        Box existBox = boxService.getById(productId);
        if (existBox == null) {
            throw new ServiceException("产品不存在");
        }
        // 构造 Box 更新对象
        Box box = new Box();
        box.setId(productId);  // 使用订单中的 productId
        box.setProductName(vo.getProductName());
        box.setLength(vo.getLength());
        box.setWidth(vo.getWidth());
        box.setHeight(vo.getHeight());
        box.setOrderQuantity(vo.getOrderQuantity());
        box.setFluteType(vo.getFluteType());
        box.setArea(vo.getArea() != null ? vo.getArea() : BigDecimal.ZERO);
        BigDecimal salePrice = vo.getSalePrice() != null ? vo.getSalePrice() : existBox.getSalePrice();
        BigDecimal rebate = vo.getRebate() != null ? vo.getRebate() : existBox.getRebate();
        box.setSalePrice(salePrice);
        box.setRebate(rebate);
        box.setProfit(salePrice.subtract(rebate));
        // 执行 Box 更新
        boxService.updateById(box);
        // 构造订单更新对象（只更新允许修改字段）
        Orders orderUpdate = new Orders();
        orderUpdate.setId(vo.getId());
        orderUpdate.setCustomerName(vo.getCustomerName());

        // 执行订单更新
        this.updateById(orderUpdate);
    }



    private OrderStatus getNextStatus(OrderStatus current) {
        switch (current) {
            case DRAFT:
                return OrderStatus.REQUESTED;
            case REQUESTED:
                return OrderStatus.IN_STOCK;
            case IN_STOCK:
                return OrderStatus.OUT_STOCK;
            default:
                throw new ServiceException("已是最终状态，无法推进");
        }
    }




}




